package com.fishbone.cloud.auth.security.handler;

import com.fishbone.cloud.auth.exception.FishBoneAuthException;
import com.fishbone.common.utils.FastJsonUtil;
import com.fishbone.core.api.ResponseEntity;
import com.fishbone.core.api.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败操作
 * @ClassName MyAuthenticationFailureHandler
 * @Author huyaxi
 * @DATE 2019/8/27 9:51
 */
@Slf4j
@Component
public class FishBoneAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(FastJsonUtil.toJSONString(ResponseEntity.fail(exception.getMessage())));
    }
}
